package it.mp.multitask.factory;

import it.mp.multitask.Main;
import it.mp.multitask.R;
import it.mp.multitask.Setup;
import it.mp.multitask.adapter.AppAdapter;
import it.mp.multitask.bean.App;
import it.mp.multitask.utility.AppComparator;
import it.mp.multitask.utility.IconManager;
import it.mp.multitask.utility.PatternEntry;
import it.mp.multitask.utility.RecentTaskInfoComparator;
import it.mp.multitask.utility.RunningServiceInfoComparator;
import it.mp.multitask.utility.RunningTaskInfoComparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class StyleDialog implements Style {

	private SharedPreferences prefs;
	private BitmapDrawable bmpCestino = null;
	private Main main = null;
	private IconManager iconManager;
	public StyleDialog(SharedPreferences prefs, BitmapDrawable bmpCestino, Main main) {
		this.prefs = prefs;
		this.bmpCestino = bmpCestino;
		this.main = main;
	}

	public void crea(int NUMERO_PROCESSI_RUNNING, int NUMERO_PROCESSI_RECENTLY, int NUMERO_PROCESSI_SERVICE, int margin, boolean alphabeticOrder) {
		main.setContentView(R.layout.main_dialog);
		ActivityManager actvityManager = (ActivityManager) main.getSystemService(Main.ACTIVITY_SERVICE);
		final GridView gridView = (GridView) main.findViewById(R.id.GW_apps);
		gridView.setBackgroundResource(android.R.drawable.dialog_frame);
		final HashSet<String> hs = new HashSet<String>();
		hs.add("it.mp.multitask##it.mp.multitask.Main");
		hs.add("com.android.phone##com.android.phone.InCallScreen");

		final boolean showRecycle = prefs.getBoolean(main.getResources().getString(R.string.app_recycle_bin), true);
		final boolean showDeleted = prefs.getBoolean(main.getResources().getString(R.string.app_show_app_deleted_by_system), false);

		iconManager = new IconManager(48, bmpCestino);

		// final ArrayList<App> al = new ArrayList<App>();
		final ArrayList<App> alRunning = new ArrayList<App>();
		final ArrayList<App> alRecently = new ArrayList<App>();
		final ArrayList<App> alPreferred = new ArrayList<App>();
		final ArrayList<App> alService = new ArrayList<App>();

		if (prefs.getBoolean(Main.PREF_APP_RUNNING, true)) {
			alRunning.addAll(getRunningApps(NUMERO_PROCESSI_RUNNING, actvityManager, hs, margin, alphabeticOrder, showRecycle, showDeleted));
		}

		final ArrayList<App> appo = getPreferredApps(hs, margin, alphabeticOrder, false);
		if (appo.size() > 0) {
			alPreferred.addAll(appo);
		}

		if (prefs.getBoolean(Main.PREF_APP_RECENTLY, true)) {
			alRecently.addAll(getRecentlyClosedApps(NUMERO_PROCESSI_RECENTLY, actvityManager, hs, margin, alphabeticOrder, false));
		}

		if (prefs.getBoolean(Main.PREF_APP_SERVICE, false)) {
			alService.addAll(getServiceApps(NUMERO_PROCESSI_SERVICE, actvityManager, hs, margin, alphabeticOrder, false, showRecycle, showDeleted));
		}
		final int patternRunning = PatternEntry.decodePattern(prefs.getString(main.getResources().getString(R.string.pref_background_theme), PatternEntry
				.primoValore()), 1);
		final int patternService = PatternEntry.decodePattern(prefs.getString(main.getResources().getString(R.string.pref_background_theme_srv), PatternEntry
				.primoValore()), 1);
		final int patternRecently = PatternEntry.decodePattern(prefs.getString(main.getResources().getString(R.string.pref_background_theme_rc), PatternEntry
				.primoValore()), 1);
		final int patternPreferred = PatternEntry.decodePattern(prefs.getString(main.getResources().getString(R.string.pref_background_theme_pa), PatternEntry
				.primoValore()), 1);

		final ArrayList<App> al = new ArrayList<App>();
		final String scrollByGroup = prefs.getString(main.getResources().getString(R.string.theme_mode), "1");
		if ("1".equals(scrollByGroup)) {
			al.addAll(alRunning);
			al.addAll(alPreferred);
			al.addAll(alRecently);
			al.addAll(alService);
		} else if ("2".equals(scrollByGroup)) {
			al.addAll(alRecently);
			al.addAll(alRunning);
			al.addAll(alPreferred);
			al.addAll(alService);
		} else if ("3".equals(scrollByGroup)) {
			al.addAll(alPreferred);
			al.addAll(alRunning);
			al.addAll(alRecently);
			al.addAll(alService);
		} else if ("4".equals(scrollByGroup)) {
			al.addAll(alService);
			al.addAll(alRunning);
			al.addAll(alRecently);
			al.addAll(alPreferred);
		}

		gridView.setAdapter(new AppAdapter(al, patternRunning, patternService, patternRecently, patternPreferred, bmpCestino));
		gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> adapter, View arg1, int posizione, long arg3) {
				final App app = (App) adapter.getItemAtPosition(posizione);
				if (app.isRunning()) {
					main.prepareKillActivity(app);
				} else if (app.isService()) {
					main.prepareKillActivity(app);
				}
				return true;
			}

		});

		gridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> adapter, View arg1, int posizione, long arg3) {
				final App app = (App) adapter.getItemAtPosition(posizione);
				if (app.isRunning()) {
					main.prepareStartActivity(app);
				} else if (app.isRecently()) {
					main.prepareStartActivity(app);
				}
			}
		});
	}

	private ArrayList<App> getRunningApps(int numero, ActivityManager actvityManager, HashSet<String> hs, int margin, boolean alphabeticOrder,
			boolean showRecycle, boolean showDeleted) {
		ArrayList<App> al = new ArrayList<App>();
		App app = null;
		int size;
		List<RunningTaskInfo> procInfos = actvityManager.getRunningTasks(numero);
		if (alphabeticOrder) {
			Collections.sort(procInfos, new RunningTaskInfoComparator(main.getPackageManager()));
		}
		size = procInfos.size();
		for (int i = 0; i < size; i++) {
			RunningTaskInfo rti = procInfos.get(i);
			if ((rti.numRunning == 0) && (!showDeleted)) {
			} else {
				try {
					app = new App(main, rti, showRecycle, iconManager);
				} catch (NameNotFoundException e) {
				}
				if (app != null) {
					if (prefs.getBoolean(app.getPackageName(), false)) {

					} else {
						if (!hs.contains(app.toString())) {
							app.setOnClickListener(main.oclStartActivity);
							app.setOnLongClickListener(main.oclKillActivity);
							al.add(app);
							hs.add(app.toString());
						}
					}
				}
			}
		}
		return al;
	}

	private ArrayList<App> getRecentlyClosedApps(int numero, ActivityManager actvityManager, HashSet<String> hs, int margin, boolean alphabeticOrder,
			boolean impostaMargine) {
		ArrayList<App> al = new ArrayList<App>();
		App app = null;
		int size;
		List<RecentTaskInfo> recInfos = actvityManager.getRecentTasks(numero + hs.size(), 0);
		if (alphabeticOrder) {
			Collections.sort(recInfos, new RecentTaskInfoComparator(main.getPackageManager()));
		}
		size = recInfos.size();
		int numApps = 0;
		for (int i = 0; i < size; i++) {
			try {
				app = new App(main, recInfos.get(i), iconManager);
			} catch (NameNotFoundException e) {
			}
			if (app != null) {
				if (prefs.getBoolean(app.getPackageName(), false)) {

				} else {
					if (!hs.contains(app.toString())) {
						numApps++;
						app.setOnClickListener(main.oclStartActivity);
						al.add(app);
						hs.add(app.toString());
					}
				}
			}
			if (numApps == numero) {
				break;
			}
		}
		return al;
	}

	private ArrayList<App> getPreferredApps(HashSet<String> hs, int margin, boolean alphabeticOrder, boolean impostaMargine) {
		ArrayList<App> alAppo = new ArrayList<App>();
		String lista = prefs.getString(main.getResources().getString(R.string.Apps_list_preferred), ";");
		StringTokenizer st = new StringTokenizer(lista, ";");
		App app = null;
		String chiave;
		HashSet<String> hsTmp=new HashSet<String>();
		while (st.hasMoreTokens()) {
			chiave = st.nextToken();
			if (prefs.getBoolean(chiave, false)) {
				chiave = chiave.replace(Setup.PREFIX_PREFERRED_APPS, "");
				try {
					app = new App(main, chiave, iconManager);
				} catch (NameNotFoundException e) {
				}
				if (app != null) {
					if (!hsTmp.contains(app.toString())) {
						app.setOnClickListener(main.oclStartActivity);
						alAppo.add(app);
						hsTmp.add(app.toString());						
					}
				}
			}
		}
		hs.addAll(hs);
		if (true) {
			if (alAppo.size() > 0) {
				Collections.sort(alAppo, new AppComparator(main.getPackageManager()));
			}
		}
		return alAppo;
	}

	private ArrayList<App> getServiceApps(int NUMERO_PROCESSI_SERVICE, ActivityManager actvityManager, HashSet<String> hs, int margin, boolean alphabeticOrder,
			boolean impostaMargine, boolean showRecycle, boolean showDeleted) {
		ArrayList<App> al = new ArrayList<App>();
		App app;
		int size;
		List<RunningServiceInfo> recInfos = actvityManager.getRunningServices(NUMERO_PROCESSI_SERVICE);
		if (alphabeticOrder) {
			Collections.sort(recInfos, new RunningServiceInfoComparator(main.getPackageManager()));
		}
		size = recInfos.size();
		RunningServiceInfo rsi = null;
		for (int i = 0; i < size; i++) {
			rsi = recInfos.get(i);
			if ((!rsi.started) && (!showDeleted)) {
			} else {
				app = new App(main, recInfos.get(i), showRecycle, iconManager);
				if (prefs.getBoolean(app.getPackageName(), false)) {

				} else {
					if (!hs.contains(app.toString())) {
						app.setOnClickListener(main.oclStartOptionPanel);
						app.setOnLongClickListener(main.oclKillActivity);
						al.add(app);
						hs.add(app.toString());
					}
				}
			}
		}
		return al;
	}

}
